package com.cfk.shopmail.auth.controller;

/*
    @CreateTime 2022/1/4 21:02
    @CreateBy cfk
*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cfk.common.constant.AuthServerConstant;
import com.cfk.common.utils.HttpUtils;
import com.cfk.common.utils.R;
import com.cfk.shopmail.auth.feign.MemeberFeignService;
import com.cfk.common.vo.MemberRespVo;
import com.cfk.shopmail.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//处理社交请求
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemeberFeignService memeberFeignService;

    // /oauth2.0/weibo/success
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1.根据code换取token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "4064755519");
        map.put("client_secret", "44908af809c45de3da8248ca1c97e733");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.shopmail.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);

        //2.处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);


            //知道当前那个社交用户
            //1.第一次登录 自动注册
            R oauthLogin = memeberFeignService.login(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功，用户信息：{}", data.toString());
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                //跳回首页
                return "redirect:http://shopmail.com";
            }else {
                return "redirect:http://auth.shopmail.com/login.html";
            }


        } else {
            return "redirect:http://auth.shopmail.com/login.html";
        }




    }
}
